<?php
namespace plugin\entity_manager\src\query;

/**
 * The MIT License
 *
 * Copyright (c) <year> <copyright holders>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author Damiano Ciarla
 * @package plugin
 * @subpackage entity_manager/class/function
 */
class Delete extends AbstractQuery implements InterfaceQuery
{
	/**
	 * Statement sql clausola where
	 *
	 * @var string
	 */
	public $_whereSql;

	/**
	 * Lista dei valori da bindare
	 *
	 * @var array
	 */
	public $_bindWhereValue = array();

	/**
	 * Limita i risultati da recuperare
	 *
	 * @var string
	 */
	public $_limitSql;
	
	/**
	 * Variabile che dichiara se si sta inserendo una condizione nella where o meno
	 *
	 * @var boolean
	 */
	private $_orClause = false;
	
	/**
	 * Variabile che dichiara se si sta inserendo una condizione nella where o meno
	 *
	 * @var string
	 */
	private $_lastField = null;

	public function __construct(\plugin\entity_manager\src\AbstractEntity $entity)
	{
		$this->_entity = &$entity;
	}

	/**
	 * Metodo che aggiunge delle custom where da eseguire o savrascrivere a quelle create
	 * dai parametri della entity
	 *
	 * <code>
	 * $User = new User();
	 *
	 * EntityManager::find($User)
	 * ->where("name")
	 * ->execute();
	 * </code>
	 *
	 * @param string $field Campo della tabella presente nella entity
	 *
	 * @return \plugin\entity_manager\src\clause\where\Delete
	 */
	public function where($field)
	{
		$properties = $this->_entity->getProperty();

		if(!key_exists($field, $properties['FIELDS']))
		{
			/**
			 * @see \plugin\entity_manager\src\exception\EntityManagerException::FIELD_NOT_FOUND_INTO_WHERE
			 */
			throw new \plugin\entity_manager\src\exception\EntityManagerException(array($field, get_class($this->_entity)), \plugin\entity_manager\src\exception\EntityManagerException::FIELD_NOT_FOUND_INTO_WHERE);
		}

		$this->_closeIfOpenOrClause();
		$this->_lastField = $field;
		return \plugin\entity_manager\src\clause\where\Delete::getInstance($this, $field);
	}
	
	/**
	 * Metodo che aggiunge una condizione OR alla WHERE dichiarata precedentemente
	 *
	 * <code>
	 * EntityManager::count(new User)
	 * ->orWhere("name")->METHOD(...)
	 * ->execute();
	 * </code>
	 *
	 * @param string $field Campo della tabella presente nella entity corrente
	 *
	 * @return \plugin\entity_manager\src\clause\where\Delete
	 */
	public function orWhere($field)
	{
		if($this->_lastField === null)
			return $this->where($field);
		
		$properties = $this->_entity->getProperty();

		if(!key_exists($field, $properties['FIELDS']))
		{
			/**
			 * @see \plugin\entity_manager\src\exception\EntityManagerException::FIELD_NOT_FOUND_INTO_WHERE
			 */
			throw new \plugin\entity_manager\src\exception\EntityManagerException(array($field, get_class($this->_entity)), \plugin\entity_manager\src\exception\EntityManagerException::FIELD_NOT_FOUND_INTO_WHERE);
		}

		if(!$this->_orClause)
			$this->_whereSql = substr_replace($this->_whereSql, " (", strrpos($this->_whereSql, $properties['ENTITY']['TABLE'] . "." . $this->_lastField) - 1, 1);
		
		$this->_orClause = true;

		return \plugin\entity_manager\src\clause\where\Delete::getInstance($this, $field, true);
	}

	/**
	 * Metodo per aggiungere un limite nella cancellazione delle informazioni
	 *
	 * <code>
	 * $User = new User();
	 * $User->name = "John";
	 *
	 * EntityManager::delete($User)
	 * ->limit(0, 20)
	 * ->execute();
	 * </code>
	 *
	 * @return Delete
	 */
	public function limit($start, $numRows)
	{
		$this->_closeIfOpenOrClause();
		$this->_limitSql = $start . ", " . $numRows;

		return $this;
	}

	/**
	 * Metodo che esegue la query costruita in base ai valori impostati nella entity
	 * o a quelli aggiuntivi settati con i metodi presenti in questa classe
	 *
	 * @return int Numero di record eliminati
	 */
	public function execute($connectionName = null)
	{
		$this->_closeIfOpenOrClause();
		$db = \plugin\entity_manager\src\EntityManager::getConfig($connectionName)->getConnection();

		$db = $db->prepare($this->_getSqlQuery());

		foreach($this->_bindWhereValue as $param)
			$db = $db->bindParam("?", $param['value'], $param['type']);

		$db = $db->execute();

		return intval($db->rowCount());
	}

	/**
	 * Metodo che si occupa di costruire la query in base ai valori impostati nella entity o ai
	 * parametri aggiuntivi settati dall'utilizzo degli altri metodi presenti in questa classe
	 *
	 * @return string
	 */
	private function _getSqlQuery()
	{
		$properties = $this->_entity->getProperty();

		$sql  =	"DELETE FROM " . $properties['ENTITY']['TABLE'] . " ";

		$sql .=	"WHERE 1 " . $this->_whereSql . " ";

		foreach($properties['FIELDS'] as $field => $property)
		{
			if($property['value'] !== null)
			{
				$sql .= " AND " . $properties['ENTITY']['TABLE'] . "." . $field . " = ?";

				$this->_bindWhereValue[] = array("type" => $this->_getBindType($property['properties']['TYPE']), "value" => $property['value']);
			}
		}

		$sql .= (($this->_limitSql !== null) ? " LIMIT " . $this->_limitSql : "");

		return $sql;
	}
	
	/**
	 * Metodo che verifica se è stata aperta la condizione OR all'interno della WHERE
	 */
	private function _closeIfOpenOrClause()
	{
		if($this->_orClause)
			$this->_whereSql .= ")";
		
		$this->_orClause = false;
	}
}
?>
